//  Copyright (c) 2013年 mafengwo All rights reserved.
//  Created by hanfeng on 12-11-29.

#import "UIFont+Addition.h"

#define __SAFE_AUTO_RELEASED_CTREF(CTValue)  ((void*)[(id)(CTValue) autorelease])
#define __SAFE_AUTO_RELEASED_CFREF(CFValue)  ((void*)[NSMakeCollectable(CFValue) autorelease])

CGFloat CTFontGetLineHeight(CTFontRef font)
{
    return CTFontGetAscent(font) + CTFontGetDescent(font);// + CTFontGetLeading(font);
}

@implementation UIFont (MTAddition)

- (CTFontRef)CTFont
{
    //    CGFloat scale = [UIScreen mainScreen].scale;
    //    CGAffineTransform scaleTransform = CGAffineTransformMakeScale(scale, scale);
    CTFontRef font = CTFontCreateWithName((CFStringRef)self.fontName, self.pointSize, NULL);
    return __SAFE_AUTO_RELEASED_CTREF(font);
}

+ (UIFont *)fontWithCTFont:(CTFontRef)ctFont
{
    NSString *fontName = [(NSString *)CTFontCopyName(ctFont, kCTFontPostScriptNameKey) autorelease];
    CGFloat fontSize = CTFontGetSize(ctFont);
    return [UIFont fontWithName:fontName size:fontSize];
}

+ (CTFontRef)CTFontWithFilePath:(NSString *)filePath size:(CGFloat)size
{
    // Adapted from http://stackoverflow.com/questions/2703085/how-can-you-load-a-font-ttf-from-a-file-using-core-text
    CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)filePath, kCFURLPOSIXPathStyle, false);
    CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(url);
    if (dataProvider) {
        CGFontRef theCGFont = CGFontCreateWithDataProvider(dataProvider);
        if (theCGFont) {
            CTFontRef result = CTFontCreateWithGraphicsFont(theCGFont, size, NULL, NULL);
            CFRelease(theCGFont);
            CFRelease(dataProvider);
            CFRelease(url);
            return __SAFE_AUTO_RELEASED_CTREF(result);
        }
        CFRelease(dataProvider);
    }
    CFRelease(url);
    return NULL;
}

+ (CTFontRef)bundledTTFFontNamed:(NSString *)name size:(CGFloat)size
{
    // Adapted from http://stackoverflow.com/questions/2703085/how-can-you-load-a-font-ttf-from-a-file-using-core-text
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"ttf"];
    return [self CTFontWithFilePath:path size:size];
}

+ (CGFontRef)CGFontWithFontPath:(NSString *)fontPath
{
    CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)fontPath, kCFURLPOSIXPathStyle, false);
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL(url);
    if (fontDataProvider) {
        CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider);
        CFRelease(fontDataProvider);
        CFRelease(url);
        return __SAFE_AUTO_RELEASED_CFREF(newFont);
    }
    CFRelease(url);
    return NULL;
}

@end
